import { useAppStore } from '@/store/modules/app.js'
import { useSettingsStore } from '@/store/modules/settings.js'
import { useRoutesStore } from '@/store/modules/routes.js'
import { useTagsBarStore } from '@/store/modules/tagsBar.js'
import Service from '@/utils/service.js'
import Layout from '@/components/Layout/index.vue'
import { sleep } from '@/utils/common.js'

const isDev = import.meta.env.DEV

const modules = import.meta.glob('@/views/**/*.vue')
const loadView = path => modules[`/src${path}`]

const routesWhiteList = ['/login']

isDev && routesWhiteList.push('/selectApi')

export const setupRouterGuard = router => {
  const routesStore = useRoutesStore()
  const appStore = useAppStore()
  const settingsStore = useSettingsStore()
  const tagsBarStore = useTagsBarStore()
  const generateRoutes = (treeRoutes, parentRoute = '') => {
    treeRoutes.forEach(route => {
      if (route.children && route.children.length > 0) {
        generateRoutes(route.children, route)
      }
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (typeof route.component === 'string') {
        route.component = loadView(route.component)
      }
      router.addRoute(parentRoute, route)
    })
  }

  const inWhiteList = to => routesWhiteList.includes(to.path)

  const isLoaded = to => {
    const currentTag = tagsBarStore.visitedRoutes.find(item => item.path === to.path)
    return !!currentTag?.loaded
  }

  router.beforeEach(async (to, from, next) => {
    Service.cancelAllRequests()

    // if (!appStore.token) {
    //   if (inWhiteList(to)) {
    //     next()
    //     return
    //   }
    //   next(`/login?redirect=${to.path}`)
    //   return
    // }

    if (routesStore.treeRoutes.length === 0) {
      const treeRoutes = await routesStore.setRoutes()
      generateRoutes(treeRoutes)
      next({ ...to, replace: true })
      return
    }

    if (!inWhiteList(to) && !isLoaded(to)) {
      settingsStore.setPageLoadingAction(true)
    }
    next()
  })

  router.afterEach(async (to, from) => {
    if (!inWhiteList(to)) {
      routesStore.updateMenu(to)
      tagsBarStore.addTabs(to)
      await sleep(220)
      settingsStore.setPageLoadingAction(false)
    }
  })
}
